package com.tea.dhcBatis.sqlSession.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.tea.dhcBatis.cfg.Configuration;
import com.tea.dhcBatis.sqlSession.SqlSession;
import com.tea.dhcBatis.sqlSession.proxy.MapperProxy;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

public class SqlSessionImpl implements SqlSession {
    private Configuration cfg;
    private Connection connection;

    public SqlSessionImpl(Configuration cfg) {
        this.cfg = cfg;
        connection=getConnection(cfg);
    }

    /**
     * 用于创建代理
     * @param mapperInterfaceClass mapper的接口字节码
     * @param <T>
     * @return
     */
    public <T> T getMapper(Class<T> mapperInterfaceClass) {
        return (T) Proxy.newProxyInstance(mapperInterfaceClass.getClassLoader(),
                new Class[]{mapperInterfaceClass},
                new MapperProxy(cfg.getMappers(),connection));
    }

    public void close() {
        if(connection !=null){
            try{
                connection.close();
            }catch (SQLException E){
                E.printStackTrace();
            }
        }
    }
    public static Connection getConnection(Configuration cfg){
        try {
            // 创建数据源
            DruidDataSource dataSource = new DruidDataSource();
            // 设置数据库连接参数
            dataSource.setDriverClassName(cfg.getDriver());
            dataSource.setUrl(cfg.getUrl());
            dataSource.setUsername(cfg.getUsername());
            dataSource.setPassword(cfg.getPassword());
            return dataSource.getConnection();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
